package com.subway.babynote.syncservice;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import com.subway.babynote.syncdata.ClientDataRecord;
import com.subway.babynote.syncdata.ClientDataRecordBase;
import com.subway.babynote.syncdata.wrapper;

import com.subway.babynote.syncservice.taskList.tsPair;

import android.content.Context;
import android.util.Log;

public class RunnableTask implements Runnable {

	private final Integer waitobj = new Integer(0);
	private final int wait_ms = 1000*3600;
	
	private taskHelp_impl th  = new taskHelp_impl();
	private Context _cnt = null;
	int flag = 0;
	public RunnableTask(Context context)
	{
		this._cnt = context;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		//initialize to get ps
		boolean bret = false;
		int iret = 0;		
		//bret = dataManager.Init();
		bret = HardwareHelper.Init(this._cnt);		
		bret = th.init(this._cnt, this);
		boolean hasrecord = false;
		if(bret)
		{
			int user_id = -1;
			int client_id = -1;
			boolean isuser = false;
			
			ClientDataRecord.usersRecord ur = th.getuser();
			if(ur != null)
			{
				hasrecord = true;
				user_id = ur.user_id;
				client_id = th.getclientid();
				isuser = ur.isuser;
			}			
			deviceManager dm = HardwareHelper.getDM();
			uai_Sing.init(user_id, dm.getIMSI(), dm.getIMEI(),client_id,isuser);
			
		}
		
		while(true)
		{
			try
			{
				if(uai_Sing.get_uai().id <0)
				{
					if(hasrecord)
					{					
						iret = th.regVisitor();
					}
				}
				if(uai_Sing.get_uai().id>=0)
				{
					if(th.haswork())
						iret = th.addtoServer();
					if(iret >= 0)
					{
						if(th.haswork())
							iret = th.addtoServer();
					}
				}				
					
			}
			catch(Exception ex)
			{
				Log.i("error in Runtask", ex.getMessage());
			}
			
			this.hang_sleep();
		}
		
		//build task list
		
		//get ps list
	}
	

	private boolean hang_sleep()
	{
		try 
		{
			synchronized(waitobj)
			{	
				waitobj.wait(this.wait_ms);		
			}
			
			return true;
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}		
	}
	public boolean hang_wake()
	{
		try 
		{
			synchronized(waitobj)
			{	
				waitobj.notifyAll();		
			}
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}	
	}
	public boolean set_work_state(int code, int ts)
	{
		taskList.tsPair tspair = dataManager.tl.get().get_tspair(code);
		if(tspair ==  null)
			return false;
		tspair.set_client_ts(ts);				
		boolean b = this.hang_wake();
		return b;		
	}
}
